package com.studyroom.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.studyroom.common.Result;
import com.studyroom.entity.Snack;
import com.studyroom.service.SnackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/snacks")
public class SnackController {

    @Autowired
    private SnackService snackService;

    @GetMapping
    public Result<Page<Snack>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice,
            @RequestParam(required = false) Integer minStock,
            @RequestParam(required = false) Integer maxStock,
            @RequestParam(required = false) Integer status) {
        Page<Snack> page = snackService.getSnackPage(
            new Page<>(current, size), name, minPrice, maxPrice, minStock, maxStock, status);
        return Result.success(page);
    }

    @PostMapping
    public Result<?> add(@RequestBody Snack snack) {
        snackService.save(snack);
        return Result.success();
    }

    @PutMapping("/{id}")
    public Result<?> update(@PathVariable Long id, @RequestBody Snack snack) {
        snack.setId(id);
        snackService.updateById(snack);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        snackService.removeById(id);
        return Result.success();
    }

    @PutMapping("/{id}/status")
    public Result<?> updateStatus(@PathVariable Long id, @RequestBody Snack snack) {
        Snack existSnack = snackService.getById(id);
        if (existSnack == null) {
            return Result.error("零食不存在");
        }
        existSnack.setStatus(snack.getStatus());
        snackService.updateById(existSnack);
        return Result.success();
    }
} 